const BaseController = require("../base");
const fs = require("mz/fs");
const path = require("path");
const pump = require("mz-modules/pump");
const moment = require("moment");

class UploadController extends BaseController {
  async index() {
    const { ctx } = this;

    const file = ctx.request.files[0];
    let filePath;

    try {
      filePath = await this.generatePath(file);
      const targetPath = path.join(this.config.baseDir, "app", filePath);
      const source = fs.createReadStream(file.filepath);
      const target = fs.createWriteStream(targetPath);
      await pump(source, target);
      ctx.logger.warn("save %s to %s", file.filepath, targetPath);
    } finally {
      // delete those request tmp files
      await ctx.cleanupRequestFiles();
    }

    filePath = `http://${ctx.header.host}${filePath}`;

    const data = await ctx.service.product.upload.index({ imgUrl: filePath, imgName: file.filename });

    this.success(data);
  }

  async generatePath(file) {
    const nowTime = Date.now();
    const filename = nowTime + path.extname(file.filename);
    // 为每一天创建文件夹
    const m = moment(nowTime);
    const year = m.year();
    const month = m.month() + 1;
    const date = m.date();

    const arr = [year, month, date];

    const basePath = path.join(this.config.baseDir, "app");
    let filePath = `/public/uploads`;

    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      filePath += `/${item}`;
      await this.mkDir(basePath + filePath);
    }

    return filePath + `/${filename}`;
  }

  async mkDir(path) {
    try {
      await fs.stat(path);
    } catch {
      await fs.mkdir(path);
    }
  }
}

module.exports = UploadController;
